package tech.yunjing.train.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * purpose: 定义需要用的redis Hash的方法
 * Created by 吕祥 on 2017/6/11.
 */
public class LoginRedisService<T> {

    @Autowired
    protected RedisTemplate<String, Object> redisTemplate;

    @Resource
    protected HashOperations<String, String, T> hashOperations;

    private static final String REDIS_KEY = "USER_INFO";
    /**
     * 存入redis中的key
     *
     * @return USER_INFO Map表名
     */
    protected String getRedisKey() {
        return this.REDIS_KEY;
    }

    /**
     * 添加
     *
     * @param key    key
     * @param doamin 对象
     * @param expire 过期时间(单位:秒),传入 -1 时表示不设置过期时间
     */
    public void userInfoPut(String key, T doamin, long expire) {
        hashOperations.put(getRedisKey(), key, doamin);
        if (expire != -1) {
            redisTemplate.expire(getRedisKey(), expire, TimeUnit.SECONDS);
        }
    }

    /**
     * 根据用户账号查找
     * @param userAccount 查询的key
     * @return 用户信息对象
     */
    public T getUserAccountKey(String userAccount) {
        return hashOperations.get(getRedisKey(), userAccount);
    }
}
